import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Dimensions,
  TouchableOpacity,
} from 'react-native';
import {LineChart, PieChart} from 'react-native-chart-kit';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage';

const screenWidth = Dimensions.get('window').width;

const Dashboard = () => {
  const [weightData, setWeightData] = useState([]);
  const [dietData, setDietData] = useState([]);
  const [exerciseData, setExerciseData] = useState([]);
  const [stats, setStats] = useState({
    currentWeight: 0,
    initialWeight: 0,
    weightLoss: 0,
    totalDays: 0,
    totalCaloriesBurned: 0,
  });

  // 从AsyncStorage加载数据
  useEffect(() => {
    const loadData = async () => {
      try {
        const weightJson = await AsyncStorage.getItem('weightData');
        const dietJson = await AsyncStorage.getItem('dietData');
        const exerciseJson = await AsyncStorage.getItem('exerciseData');

        if (weightJson) setWeightData(JSON.parse(weightJson));
        if (dietJson) setDietData(JSON.parse(dietJson));
        if (exerciseJson) setExerciseData(JSON.parse(exerciseJson));
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    };

    loadData();
  }, []);

  // 计算统计数据
  useEffect(() => {
    if (weightData.length > 0) {
      const currentWeight = weightData[weightData.length - 1].weight;
      const initialWeight = weightData[0].weight;
      const weightLoss = initialWeight - currentWeight;
      const totalDays = weightData.length;
      const totalCaloriesBurned = exerciseData.reduce(
        (sum, exercise) => sum + exercise.calories,
        0,
      );

      setStats({
        currentWeight,
        initialWeight,
        weightLoss,
        totalDays,
        totalCaloriesBurned,
      });
    }
  }, [weightData, exerciseData]);

  // 准备图表数据
  const prepareChartData = () => {
    // 最多显示7个数据点
    const displayData = weightData.slice(-7);

    return {
      labels: displayData.map(entry => {
        const date = new Date(entry.date);
        return `${date.getMonth() + 1}/${date.getDate()}`;
      }),
      datasets: [
        {
          data: displayData.map(entry => entry.weight),
          color: (opacity = 1) => `rgba(102, 126, 234, ${opacity})`,
          strokeWidth: 2,
        },
      ],
    };
  };

  // 准备运动类型分布数据
  const prepareExerciseData = () => {
    const exerciseTypes = {};

    exerciseData.forEach(exercise => {
      if (exerciseTypes[exercise.type]) {
        exerciseTypes[exercise.type] += 1;
      } else {
        exerciseTypes[exercise.type] = 1;
      }
    });

    const colors = [
      '#FF6384',
      '#36A2EB',
      '#FFCE56',
      '#4BC0C0',
      '#9966FF',
      '#FF9F40',
    ];

    return Object.keys(exerciseTypes).map((type, index) => ({
      name: type,
      count: exerciseTypes[type],
      color: colors[index % colors.length],
      legendFontColor: '#7F7F7F',
      legendFontSize: 12,
    }));
  };

  const chartConfig = {
    backgroundGradientFrom: '#fff',
    backgroundGradientTo: '#fff',
    decimalPlaces: 1,
    color: (opacity = 1) => `rgba(102, 126, 234, ${opacity})`,
    labelColor: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
    style: {
      borderRadius: 16,
    },
    propsForDots: {
      r: '6',
      strokeWidth: '2',
      stroke: '#667eea',
    },
  };

  return (
    <ScrollView style={styles.container}>
      {/* 统计卡片 */}
      <View style={styles.statsContainer}>
        <View style={styles.statCard}>
          <Icon name="monitor-weight" size={24} color="#667eea" />
          <Text style={styles.statValue}>
            {stats.currentWeight.toFixed(1)} kg
          </Text>
          <Text style={styles.statLabel}>当前体重</Text>
        </View>

        <View style={styles.statCard}>
          <Icon name="trending-down" size={24} color="#667eea" />
          <Text style={styles.statValue}>
            {stats.weightLoss > 0
              ? `-${stats.weightLoss.toFixed(1)}`
              : `+${Math.abs(stats.weightLoss).toFixed(1)}`}{' '}
            kg
          </Text>
          <Text style={styles.statLabel}>体重变化</Text>
        </View>

        <View style={styles.statCard}>
          <Icon name="local-fire-department" size={24} color="#667eea" />
          <Text style={styles.statValue}>
            {stats.totalCaloriesBurned.toFixed(0)}
          </Text>
          <Text style={styles.statLabel}>消耗卡路里</Text>
        </View>
      </View>

      {/* 体重变化图表 */}
      <View style={styles.chartCard}>
        <Text style={styles.chartTitle}>体重变化趋势</Text>
        {weightData.length > 0 ? (
          <LineChart
            data={prepareChartData()}
            width={screenWidth - 40}
            height={220}
            chartConfig={chartConfig}
            bezier
            style={styles.chart}
          />
        ) : (
          <View style={styles.noDataContainer}>
            <Text style={styles.noDataText}>暂无体重数据</Text>
          </View>
        )}
      </View>

      {/* 运动类型分布 */}
      <View style={styles.chartCard}>
        <Text style={styles.chartTitle}>运动类型分布</Text>
        {exerciseData.length > 0 ? (
          <PieChart
            data={prepareExerciseData()}
            width={screenWidth - 40}
            height={220}
            chartConfig={chartConfig}
            accessor="count"
            backgroundColor="transparent"
            paddingLeft="15"
            absolute
          />
        ) : (
          <View style={styles.noDataContainer}>
            <Text style={styles.noDataText}>暂无运动数据</Text>
          </View>
        )}
      </View>

      {/* 成就卡片 */}
      {stats.weightLoss > 0 && (
        <View style={styles.achievementCard}>
          <Icon name="emoji-events" size={30} color="#FFD700" />
          <View style={styles.achievementContent}>
            <Text style={styles.achievementTitle}>恭喜你！</Text>
            <Text style={styles.achievementText}>
              你已经成功减重 {stats.weightLoss.toFixed(1)} kg，继续保持！
            </Text>
          </View>
        </View>
      )}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 15,
  },
  statsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 15,
  },
  statCard: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 15,
    alignItems: 'center',
    width: '31%',
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  statValue: {
    fontSize: 18,
    fontWeight: 'bold',
    marginTop: 8,
    color: '#333',
  },
  statLabel: {
    fontSize: 12,
    color: '#666',
    marginTop: 4,
  },
  chartCard: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 15,
    marginBottom: 15,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  chartTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  chart: {
    marginVertical: 8,
    borderRadius: 16,
  },
  noDataContainer: {
    height: 220,
    justifyContent: 'center',
    alignItems: 'center',
  },
  noDataText: {
    color: '#999',
    fontSize: 16,
  },
  achievementCard: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 15,
    marginBottom: 15,
    flexDirection: 'row',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  achievementContent: {
    marginLeft: 15,
    flex: 1,
  },
  achievementTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
  },
  achievementText: {
    fontSize: 14,
    color: '#666',
    marginTop: 4,
  },
});

export default Dashboard;
